package com.igeek.oa.service.impl;

import cn.hutool.core.io.resource.ClassPathResource;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.igeek.oa.entity.Officesupplies;
import com.igeek.oa.entity.OfficesuppliesApply;
import com.igeek.oa.entity.Offsupapply;
import com.igeek.oa.mapper.OfficesuppliesApplyMapper;
import com.igeek.oa.mapper.OfficesuppliesMapper;
import com.igeek.oa.mapper.OffsupapplyMapper;
import com.igeek.oa.result.Result;
import com.igeek.oa.service.IOffsupapplyService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 办公用品申请表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-08-28
 */
@Service
public class OffsupapplyServiceImpl extends ServiceImpl<OffsupapplyMapper, Offsupapply> implements IOffsupapplyService {
    @Autowired
    private OffsupapplyMapper offsupapplyMapper;
    @Autowired
    private OfficesuppliesMapper officesuppliesMapper;
    @Autowired
    JavaMailSender javaMailSender;

    @Transactional
    @Override
    public Offsupapply addOffsupapply(String eId) {
        String format = "yyyy-MM-dd HH:mm:ss";
        LocalDateTime localDateTime = LocalDateTime.now();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
        String time = localDateTime.format(dateTimeFormatter);
        LocalDateTime parse = LocalDateTime.parse(time, dateTimeFormatter);
        String aId = UUID.randomUUID().toString().substring(1,6);
        Offsupapply offsupapply = new Offsupapply();
        offsupapply.setaId(aId);
        offsupapply.seteId(eId);
        offsupapply.setState("0");
        offsupapply.setApplyTime(parse);
        offsupapplyMapper.insert(offsupapply);
        return offsupapply;
    }

    @Override
    public Result sendFile(String email,MultipartFile file) {
        //发送人
        String from = "1003093373@qq.com";
        //接收人
        String to = email;
        //标题
        String subject = "测试邮件";
        try {
            //正文
            String context1 = "办公用品申请excel";
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //支持携带附件
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
            messageHelper.setFrom(from+"(徐恒云)");
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            //支持正文解析html内容
            messageHelper.setText(context1);
            //添加附件
            File newFile = null;
            try {
            String path = "classpath:template/test.xlsx";
            newFile = ResourceUtils.getFile(path);
                if (!newFile.exists()) {
                    newFile.createNewFile();
                }
                // 底层也是通过io流写入文件file
                FileCopyUtils.copy(file.getBytes(), newFile);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
//            File file = ResourceUtils.getFile("classpath:徐恒云.md");
            messageHelper.addAttachment(file.getName(),newFile);
            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
        return new Result(true,"发送成功","邮件已发送");
    }

    @Override
    public Result getExcel(MultipartFile file) {
            File newFile = null;
            List<Officesupplies> list = new ArrayList<>();
            try {
                String path = "classpath:template/test.xlsx";
                newFile = ResourceUtils.getFile(path);
                if (!newFile.exists()) {
                    newFile.createNewFile();
                }
                FileCopyUtils.copy(file.getBytes(), newFile);
                InputStream inputStream = new FileInputStream(newFile);
                XSSFWorkbook excel = new XSSFWorkbook(inputStream);
                XSSFSheet sheet = excel.getSheetAt(0);
                for(Row row:sheet){
                    if(row.getRowNum() > 0){
                    Officesupplies officesupplies = new Officesupplies();
                    for (Cell cell:row){
                        if(cell != null){
                            cell.setCellType(Cell.CELL_TYPE_STRING);
                            if(cell.getColumnIndex() == 0){
                                officesupplies.setOId(cell.getStringCellValue());
                            }
                            else if(cell.getColumnIndex() == 1){
                                officesupplies.setOName(cell.getStringCellValue());
                            }
                            else {
                                LambdaQueryWrapper<Officesupplies> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                                Officesupplies officesupplies1 =  officesuppliesMapper.selectOne(lambdaQueryWrapper.eq(Officesupplies::getOName,officesupplies.getOName()));
                                if(officesupplies1 == null){
                                    officesupplies.setUsedNum(0l);
                                }
                                else {
                                    officesupplies.setUsedNum(Long.parseLong(cell.getStringCellValue()));
                                }
                            }
                        }
                    }
                    list.add(officesupplies);
                    }
                }

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
          return new Result(true,"excel上传成功",list);
    }
}
